/**
 * 
 */
package com.dfhc.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.quickbundle.tools.helper.RmJspHelper;

import com.dfhc.ISystemConstant;

/**
 * @author 龙色波 检查csrf 随机数
 */
public class CsrfHelper {

	/**
	 * 检查csrf 码
	 * 
	 * @param request
	 */
	public static boolean checkCsrfCode(HttpServletRequest request) {
		String csrfCode = request.getParameter(ISystemConstant.CSRF_CODE);
		if (csrfCode == null) {
			csrfCode = "";
		}
		// 更新session
		HttpSession session = RmJspHelper.getSession(request, false);
		String sessionCsrfCode = (String) session.getAttribute(ISystemConstant.CSRF_CODE);
		if (!csrfCode.equals(sessionCsrfCode)) {
			return false;
		} else {
			return true;
		}

	}

	/**
	 * 产生csrf 随机数
	 * 
	 * @param request
	 */
	public static void produceCsrfCode(HttpServletRequest request) {
		String uuid = StringHelper.getUUID();
		request.setAttribute(ISystemConstant.CSRF_CODE, uuid);
		// 更新session
		HttpSession session = RmJspHelper.getSession(request, false);
		session.setAttribute(ISystemConstant.CSRF_CODE, uuid);
	}

	/**
	 * 从session获取csrf 随机数
	 * 
	 * @param request
	 */
	public static String getCsrfCode(HttpServletRequest request) {
		HttpSession session = RmJspHelper.getSession(request, false);
		return (String) session.getAttribute(ISystemConstant.CSRF_CODE);
	}

	/**
	 * 获取csrf 随机数
	 * 
	 * @param request
	 */
	public static void resetCsrfCode(HttpServletRequest request) {
		String csrfCode = request.getParameter(ISystemConstant.CSRF_CODE);
		HttpSession session = RmJspHelper.getSession(request, false);
		session.setAttribute(ISystemConstant.CSRF_CODE, csrfCode);
	}
}
